package com.itcast.rpc.core.client;

import com.itcast.rpc.core.base.RpcRequest;
import com.itcast.rpc.core.client.initializer.ClientInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @program: bio_tcp
 * @description: tcp 粘包和拆包的客户端
 * @author: zhanghz001
 * @create: 2021-02-23 10:48
 **/
public class NettyRpcClient {
    private Channel channel;
    private EventLoopGroup worker;
    
    public void start(String host, int port) {
        try {
            doStart(host, port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private void doStart(String host, int port) throws Exception {
        worker = new NioEventLoopGroup();
        try {
            //创建客户端启动类
            Bootstrap bootstrap = new Bootstrap();
            
            //指定线程池
            bootstrap.group(worker);
            //指定channel的类型
            bootstrap.channel(NioSocketChannel.class);
            //绑定处理的channel pipeline
            bootstrap.handler(new ClientInitializer());
            
            //连接服务端
            ChannelFuture future = bootstrap.connect(host, port).sync();
            System.out.println("客户端连接成功");
            channel = future.channel();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
    
    public void close() {
        if (null != this.channel && this.channel.isActive()) {
            this.channel.close();
        }
        if (null != this.worker && !this.worker.isShutdown()) {
            this.worker.shutdownGracefully();
        }
    }
    
    /**
     * 发送消息
     *
     * @param request
     */
    public void sendMsg(RpcRequest request) {
        channel.eventLoop().execute(new Runnable() {
            @Override
            public void run() {
                channel.writeAndFlush(request);
            }
        });
    }
}

